package com.game.gameevent;

import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import com.kodgames.httpserver.IRequestListener;
import com.kodgames.httpserver.KodHttpMessage;

public class HttpRequestListener implements IRequestListener
{
	private static Logger logger = LoggerFactory.getLogger(HttpRequestListener.class);
	private static final String GAME_HEADER = "/game_event";
	private static final String ERROR_HEADER = "/error_event";
	private static final String DOWNLOAD_HEADER = "/download_event";
	private static final String RESULT_SUCCESS = "{ \"code\" : 1 }";
	private static final String RESULT_FAILED = "{ \"code\" : 0 }";
	private static final char SPLIT = 0x01;

	@Override
	public String execute(KodHttpMessage msg)
	{
		String uri = msg.getUri();
//		logger.debug("GameEvent HttpRequestListener URI {}", uri);
		if (uri.startsWith(ERROR_HEADER))
		{
			HashMap<String, Object> param = (HashMap<String, Object>)msg.getMapUri();
			StringBuffer sb = new StringBuffer();
			sb.append(SPLIT);
			sb.append(param.get("error"));
			MDC.put("LOG_NAME", "error_event");
			logger.info(sb.toString());
			return RESULT_SUCCESS;
		}
		if (uri.startsWith(DOWNLOAD_HEADER))
		{
			HashMap<String, Object> param = (HashMap<String, Object>)msg.getMapUri();
			StringBuffer sb = new StringBuffer();
			sb.append(SPLIT);
			sb.append(param.get("uri"));
			sb.append(SPLIT);
			sb.append(param.get("address"));
			MDC.put("LOG_NAME", "download_event");
			logger.info(sb.toString());
			return RESULT_SUCCESS;
		}
		if (uri.startsWith(GAME_HEADER))
		{
			HashMap<String, Object> param = (HashMap<String, Object>)msg.getMapUri();
			StringBuffer sb = new StringBuffer();
			sb.append(SPLIT);
			sb.append(param.get("deviceid"));
			sb.append(SPLIT);
			sb.append(param.get("accountid"));
			sb.append(SPLIT);
			sb.append(param.get("platform"));
			sb.append(SPLIT);
			sb.append(param.get("channelid"));
			sb.append(SPLIT);
			sb.append(param.get("eventid"));
			MDC.put("LOG_NAME", "game_event");
			logger.info(sb.toString());
			return RESULT_SUCCESS;
		}
		return RESULT_FAILED;
	}
	
	@Override
	public String sendError()
	{
		return RESULT_FAILED;
	}
}
